#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Build-in / Std

'''
Created on 2016年8月23日

@author: Hawk
'''

from peewee import IntegrityError
from model.Model import *
from command_util import run_command
from util.Singleton import Singleton
from misc.ErrorMessage import ErrorMessage

_db_name_ = "projects.db"

class SkuMgr(Singleton):
    def __init__(self):
        pass
    def get_skus(self):
        return Sku.select().get()

    def add_sku(self, name, comment=''):
        try:
            sk = Sku.create_with_args(name=name, comment=comment)
            return sk.save() > 0
        except IntegrityError as e:
            return ErrorMessage(False, e.message)

    def del_sku(self, id=None, name=None):
        sku = None
        if id is not None:
            sku = Sku.getOne(Sku.id == id)
        elif name is not None:
            sku = Sku.getOne(Sku.name == name)

        if sku:
            sku.deleted = True
            return sku.save() > 0

        return ErrorMessage(False, 'record not exist')

class CategoryMgr(Singleton):
    def __init__(self):
        pass
    def get_categories(self):
        return Category.select().get()
    def add_category(self, name, comment=''):
        try:
            sk = Category.create_with_args(name=name, comment=comment)
            return sk.save() > 0
        except IntegrityError as e:
            return ErrorMessage(False, e.message)
    def del_category(self, id=None, name=None):
        category = None
        if id is not None:
            category = Category.getOne(Category.id == id)
        elif name is not None:
            category = Category.getOne(Category.name == name)

        if category:
            category.deleted = True
            return category.save() > 0

        return ErrorMessage(False, 'record not exist')

class ProjectMgr(Singleton):
    def __init__(self):
        pass
    def get_projects(self):
        return Project.select().get()
    def add_project(self, name, category, owner, ee_owner, comment):
        try:
            pro = Project.create_with_args(name=name, category=category, owner=owner, ee_owner=ee_owner, comment=comment)
            return pro.save() > 0
        except IntegrityError as e:
            return ErrorMessage(False, e.message)
    def del_project(self, id=None, name=None):
        project = None
        if id is not None:
            project = Project.getOne(Project.id == id)
        elif name is not None:
            project = Project.getOne(Project.name == name)

        if project:
            project.deleted = True
            return project.save() > 0

        return ErrorMessage(False, 'record not exist')

class ProductMgr(Singleton):
    def __init__(self):
        pass
    def get_products(self):
        def sum_attr_value(list_obj, attr):
            return sum([ getattr(item, attr) for item in list_obj])
        products = Product.select().where(Product.deleted == False)
        for product in products:
            setattr(product, 'development_mm', sum_attr_value(product.records, 'development_mm'))
            setattr(product, 'maintenance_mm', sum_attr_value(product.records, 'maintenance_mm'))
        return products
    def add_product(self, project, sku, owner,
                    frm107_date, mp_date, comment):
        if Product.getOne((Product.project == project) & (Product.sku == sku)) is not None:
            return ErrorMessage(False, 'Record exists!')
        try:
            pro = Product.create_with_args(
                        project=project, sku=sku,
                        owner=owner,
                        frm107_date=frm107_date, mp_date=mp_date,
                        comment=comment)
            return pro.save() > 0
        except IntegrityError as e:
            return ErrorMessage(False, e.message)
    def del_product(self, id=None):
        product = None
        if id is not None:
            product = Product.getOne(Product.id == id)

        if product:
            product.deleted = True
            return product.save() > 0

        return ErrorMessage(False, 'record not exist')

class RecordMgr:
    def __init__(self):
        pass
    def get_records(self):
        return Record.select().get()
    def add_record(self, date, product, version, ww_version, ww_release_date, development_mm, maintenance_mm, is_sync_ww, comment):
        if Record.getOne((Record.date == date) & (Record.product == product) & (Record.version == version)) is not None:
            return ErrorMessage(False, 'Record exists!')
        try:
            pro = Record.create_with_args(
                        date=date, product=product,
                        version=version, ww_version=ww_version,
                        ww_date=ww_release_date,
                        development_mm=development_mm, maintenance_mm=maintenance_mm,
                        is_sync_ww=is_sync_ww,
                        comment=comment)
            return pro.save() > 0
        except IntegrityError as e:
            return ErrorMessage(False, e.message)
    def del_record(self, id=None):
        record = None
        if id is not None:
            record = Record.getOne(Record.id == id)

        if record:
            record.deleted = True
            return record.save() > 0

        return ErrorMessage(False, 'record not exist')

class Action(Singleton):
    success = False
    def __init__(self):
        self.success = False

    def open_db(self, database_path=""):
        self.success = False

        #print database_path if os.path.exists(database_path) else _db_name_
        database = SqliteDatabaseWarpper(database_path if os.path.exists(database_path) else _db_name_)

        try:
            database.get_tables()

            self.success = True

            database.register(Category)
            database.register(Project)
            database.register(Sku)
            database.register(Record)
            database.register(Product)
            database.register(Operation)

            self.SkuMgr = SkuMgr()
            self.CategoryMgr = CategoryMgr()
            self.ProjectMgr = ProjectMgr()
            self.ProductMgr = ProductMgr()
            self.RecordMgr = RecordMgr()
        except:
            pass

    def create_new_db(self, database_path):
        database = SqliteDatabaseWarpper(database_path)

        database.register(Category)
        database.register(Project)
        database.register(Sku)
        database.register(Record)
        database.register(Product)
        database.register(Operation)

        self.success = False

        try:
            database.connect()
            database.create_tables([Category, Project, Sku, Record, Product, Operation], safe=True)
            self.success = True
        except:
            pass

if __name__ == '__main__':
    print SkuMgr().add_sku('CHN512', 'here is comment')
    print SkuMgr().del_sku(id=1)
    print SkuMgr().del_sku(name='CHN5')
    print CategoryMgr().aad_category('Aviation', '飞机')
